<?php

/*
	Class: Commerce_CatalogController

	About: Author
		Tyler Vigeant, Swift Collective

	About: License
		<http://communit.as/docs/license>
*/
class Commerce_CategoryadminController extends Cts_Controller_Action_Admin {

	protected $use_season = false;
	protected $use_locale = false;
	
	private $debug_mode = false;
	
	/*
		Function: init
	*/
	function init() {
		parent::init();
		
		$request = new Cts_Request($this->getRequest());
		
		if( $request->has('instance') ){
			$this->session->commerce_categoryadmin_selected_locale = $request->instance;
		}
		
		if( $this->session->commerce_categoryadmin_selected_locale == 'global' || $this->session->commerce_categoryadmin_selected_locale == '0' ){
			$this->session->commerce_categoryadmin_selected_locale = 'global';
			$this->use_locale = 0;
		} elseif( !empty($this->session->commerce_categoryadmin_selected_locale) ){
			$this->use_locale = $this->session->commerce_categoryadmin_selected_locale;
		} else {
			$this->use_locale = $this->locale_code;
		}
		
		if( $request->has('season') ){
			$this->session->commerce_categoryadmin_selected_season = (int)$request->season;
		}
		
		if( !empty($this->session->commerce_categoryadmin_selected_season) ){
			$this->use_season = (int)$this->session->commerce_categoryadmin_selected_season;
		} else {
			$seasons = Commerce_Common::getSeasons( $this->use_locale );				
			foreach( $seasons as $season ){
				if( $season['is_active']=='1' ){
					$this->use_season = $season['category_id'];
					break;
				}
			}
		}
	}

	/*
		Function: indexAction
	*/
	function indexAction() {
		$request = new Cts_Request($this->getRequest());
		$Catalog = new CommerceMagentoCatalog();
		
		$this->prepCategoryPage( $request, $Catalog );
		$storeView = $Catalog->formatStoreId($this->use_locale);
		
		if( isset($this->view->errors) ){
			$errors = (array)$this->view->errors;
		} else {
			$errors = array();
		}
		
		if( isset($this->session->errors) ){
			## make sure that this stays below prepCategoryPage()
			$errors[] = $this->session->errors;
			unset($this->session->errors);
		}
		
		$this->view->errors = $errors;
		$this->view->title = 'Category & Season Management';
		$this->view->masthead = 'Product Categories & Seasons';
	}

	/*
		Function: editAction
	*/
	function editAction() {
		$request = new Cts_Request($this->getRequest());
		$Catalog = new CommerceMagentoCatalog();
		
		## Prep the category page
		$this->prepCategoryPage( $request, $Catalog );
		$storeView = $Catalog->formatStoreId($this->use_locale);
		
		if( isset($this->view->errors) ){
			$errors = (array)$this->view->errors;
		} else {
			$errors = array();
		}
		
		## Get category info & detect category type
		$info = $Catalog->getCategory( $request->id, $storeView );
		if( $info['level'] == Cts_Registry::get('magento_root_catalog_level') ){
			$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/season/'.$request->id.'/' );
		} elseif( $info['level'] == Cts_Registry::get('magento_root_category_level') ){
			$type = 'activity';
		} elseif( isset($info['blackdiamond_swiftcollective_cat_is_spareparts']) && $info['blackdiamond_swiftcollective_cat_is_spareparts']=='1' ){
			$type = 'spare_parts';
		} elseif( isset($info['blackdiamond_swiftcollective_cat_is_kit']) && $info['blackdiamond_swiftcollective_cat_is_kit']=='1' ){
			$type = 'kit';
		} else {
			$type = 'category';
		}
		
		if( $type != 'activity' ){
			$activity = $Catalog->getCategory( $info['parent_id'], $storeView );
			$season = $Catalog->getCategory( $activity['parent_id'], $storeView );
		} else {
			$season = $Catalog->getCategory( $info['parent_id'], $storeView );
		}
		
		## Get the category information
		$info = $this->simplifyAttributeNames( $info );
		
		## Unserialize media attributes
		foreach( $info as $key=>$value ){
			$try = @unserialize($value);
			if($try!==false && is_array($try)) $info[$key] = $try;
		}

		## Associated Products
		$associated_products = $this->do_associated_products( $storeView, $request, $Catalog );
		$this->view->associated = $associated_products;
		
#### SAVING ####
		
		if( $this->getRequest()->isPost() ){
			## Catch all bdsc attributes
			foreach( $request as $key=>$value ){
				if( strstr($key, 'bdsc_') || strstr($key, 'blackdiamond_swiftcollective_') ){
					$info[$key] = $value;
				}
			}
			
			## Name
			if( !$request->has('name') || empty($request->name) ){
				$errors[] = $this->_T('Please provide a name.');
			} else {
				$info['name'] = $request->name;
			}
			
			## Kit Description
			if( $type!='kit' || !$request->has('description') || empty($request->description) ){
				$info['description'] = '';
			} else {
				$info['description'] = $request->description;
			}
			
			## Header Image
			if( $type=='activity' ){
				$info['image'] = '';
			} else {
				$info['image'] = $request->image;
			}
			
			## Listing Thumbnail
			if( $type=='activity' ){
				$info['bdsc_cat_thumb'] = '';
			}
			
			## Media
			if( $type!='kit' ){
				if( !$request->has('path') || empty($request->path) || !is_array($request->path) ){
					$info['bdsc_media_title']		= 'a:0:{}';
					$info['bdsc_media_subtitle']	= 'a:0:{}';
					$info['bdsc_media_active']		= 'a:0:{}';
					$info['bdsc_media_type']		= 'a:0:{}';
					$info['bdsc_media_path']		= 'a:0:{}';
					$info['bdsc_media_thumb_path']	= 'a:0:{}';
					$info['bdsc_media_start']		= 'a:0:{}';
					$info['bdsc_media_end']			= 'a:0:{}';
				} else {
					$media = array();
					for( $x=0; $x<count($request->path); $x++ ){
						if( !empty($request->title[$x])
						&& !empty($request->path[$x])
						&& !empty($request->type[$x])
						&& !empty($request->start[$x]) ){
							$media['order'][$x] = $x;
							$media['title'][$x] = (string)$request->title[$x];
							$media['subtitle'][$x] = (string)$request->subtitle[$x];
							$media['path'][$x] = (string)$request->path[$x];
							$media['thumb'][$x] = (string)$request->thumb[$x];
							$media['type'][$x] = (string)$request->type[$x];
							
							if( is_array($request->active) && in_array($request->path[$x], $request->active) ){
								$media['active'][$x] = '1';
							} else {
								$media['active'][$x] = '0';
							}
							
							if( strtotime($request->start[$x])!==false ){
								$media['start'][$x] = date('Y-m-d H:i:s', strtotime($request->start[$x]));
							} else {
								$media['start'][$x] = date('Y-m-d H:i:s');
							}
							
							if( strtotime($request->end[$x])!==false ){
								$media['end'][$x] = date('Y-m-d H:i:s', strtotime($request->end[$x]));
							} else {
								$media['end'][$x] = '';
							}
						} else {
							$errors[] = $this->_T('One or more of the media items is imcomplete.');
							break;
						}
					}
					
					if( count($errors)==0 ){
						$info['bdsc_media_order']		= serialize($media['order']);
						$info['bdsc_media_title']		= serialize($media['title']);
						$info['bdsc_media_subtitle']	= serialize($media['subtitle']);
						$info['bdsc_media_active']		= serialize($media['active']);
						$info['bdsc_media_type']		= serialize($media['type']);
						$info['bdsc_media_path']		= serialize($media['path']);
						$info['bdsc_media_thumb_path']	= serialize($media['thumb']);
						$info['bdsc_media_start']		= serialize($media['start']);
						$info['bdsc_media_end']			= serialize($media['end']);
					}
				}
			} else {
				$info['bdsc_media_title']		= 'a:0:{}';
				$info['bdsc_media_subtitle']	= 'a:0:{}';
				$info['bdsc_media_active']		= 'a:0:{}';
				$info['bdsc_media_type']		= 'a:0:{}';
				$info['bdsc_media_path']		= 'a:0:{}';
				$info['bdsc_media_thumb_path']	= 'a:0:{}';
				$info['bdsc_media_start']		= 'a:0:{}';
				$info['bdsc_media_end']			= 'a:0:{}';
			}

			## Related Categories
			if( $type=='activity' || $type=='kit' ){
				if( !$request->has('bdsc_related_categories') || empty($request->bdsc_related_categories) ){
					$info['bdsc_related_categories'] = '';
				} elseif( is_array($request->bdsc_related_categories) && count($request->bdsc_related_categories)>4 ){
					$errors[] = $this->_T('You may only have four related categories.');
				} else {
					$info['bdsc_related_categories'] = implode(',', (array)$request->bdsc_related_categories);
				}
			}
			
			## Defaults based on category type
			switch( $type ){
				case 'activity':
					$info['bdsc_cat_is_hidden'] = '0';
					$info['bdsc_cat_is_kit'] = '0';
					$info['bdsc_cat_is_spareparts'] = '0';
					$info['bdsc_cat_allow_comparisons'] = '0';
					break;
				case 'spare_parts':
					$info['bdsc_cat_is_hidden'] = '0';
					$info['bdsc_cat_is_kit'] = '0';
					$info['bdsc_cat_is_spareparts'] = '1';
					$info['bdsc_cat_allow_comparisons'] = '0';
					break;
				case 'kit':
					$info['bdsc_cat_is_hidden'] = ($request->has('bdsc_cat_is_hidden') && $request->bdsc_cat_is_hidden=='yes') ? '1' : '0';
					$info['bdsc_cat_is_kit'] = '1';
					$info['bdsc_cat_is_spareparts'] = '0';
					$info['bdsc_cat_allow_comparisons'] = '0';
					break;
				case 'category':
					$info['bdsc_cat_is_hidden'] = '0';
					$info['bdsc_cat_is_kit'] = '0';
					$info['bdsc_cat_is_spareparts'] = '0';
					$info['bdsc_cat_allow_comparisons'] = ($request->has('bdsc_cat_allow_comparisons') && $request->bdsc_cat_allow_comparisons=='yes') ? '1' : '0';
					break;
			}
			
			if( count($errors)==0 ){
				## Strip attributes handeled by Magento from the info going to the API
				$api = $info;
				$magento_attributes = array('is_active','position','level','parent_id','created_at','updated_at','meta_title','meta_keywords','meta_description','display_mode','is_anchor','all_children','path_in_store','children','page_layout','custom_layout_update','url_path','custom_design','custom_design_apply','path');
				
				foreach( $api as $key=>$value ){
					if( in_array($key, $magento_attributes) ){
						unset($api[$key]);
					}
				}
				
				if( $this->debug_mode ){
					$update = true;
					$api = $this->restoreAttributeNames( $api );
					d('REQUEST:'); 	d($_REQUEST);
					d('RESULTS:');	d($api);
					d('ON LOCALE:');	dd($storeView);
				} else {
					$api = $this->restoreAttributeNames( $api );
					$update = $Catalog->updateCategory( $api['category_id'], $api, $storeView );
				}

				if(!$update) $errors[] = $this->_T('There was an error updating the commerce database.');
			}
			
			## Re-unserialize media attributes
			foreach( $info as $key=>$value ){
				$try = @unserialize($value);
				if($try!==false && is_array($try)) $info[$key] = $try;
			}
		}
		
#### SMARTY ####

		## Masthead and page title
		switch($type){
			case 'spare_parts':
				$this->view->title = 'Spare Parts Management';
				if( trim(strtolower($info['name'])) == 'spare parts' ){
					$this->view->masthead = $this->_T('Editing Spare Parts').' - '.$activity['name'].' - '.$season['name'];
				} else {
					$this->view->masthead = $this->_T('Editing Spare Parts:').' '.$info['name'].' - [activity]'.' - '.$season['name'];
				}
				break;
			case 'kit':
				$this->view->title = 'Kit Management';
				$this->view->masthead = $this->_T('Editing Kit:').' '.$info['name'].' - '.$activity['name'].' - '.$season['name'];
				break;
			case 'category':
				$this->view->title = 'Category Management';
				$this->view->masthead = $this->_T('Editing Category:').' '.$info['name'].' - '.$activity['name'].' - '.$season['name'];
				break;
			case 'activity':
				$this->view->title = 'Activity Management';
				$this->view->masthead = $this->_T('Editing Activity:').' '.$info['name'].' - '.$season['name'];
				break;
		}
		
		## Build media variable
		if (!empty($info['bdsc_media_path'])) {
			for ($x = 0; $x < count($info['bdsc_media_path']); $x++) {

				$end = (!strtotime($info['bdsc_media_end'][$x])) ? '' : $info['bdsc_media_end'][$x];
				$end_formatted = (!strtotime($info['bdsc_media_end'][$x])) ? '(none)' : date('m/d/Y', strtotime($info['bdsc_media_end'][$x]));

				$info['media'][] = array(
					'title'           => $info['bdsc_media_title'][$x],
					'subtitle'        => $info['bdsc_media_subtitle'][$x],
					'active'          => (int)$info['bdsc_media_active'][$x],
					'type'            => $info['bdsc_media_type'][$x],
					'path'            => $info['bdsc_media_path'][$x],
					'thumb'           => $info['bdsc_media_thumb_path'][$x],
					'start'           => $info['bdsc_media_start'][$x],
					'start_formatted' => date('m/d/Y', strtotime($info['bdsc_media_start'][$x])),
					'end'             => $end,
					'end_formatted'   => $end_formatted,
				);
			}
		} else {
			$info['media'] = false;
		}
		
		if( $info['media'] && is_array($info['media']) && count($info['media'])>0 ){
			$this->view->has_media = true;
		} else {
			$this->view->has_media = false;
		}
		
		## Setup related category arrays for Smarty
		$related = (!empty($info['bdsc_related_categories'])) ? explode(',',$info['bdsc_related_categories']) : array();
		$this->view->category_tree_options = Commerce_Common::categoryTree_to_Options( $this->view->category_tree );
		$this->view->category_tree_options_selected = $related;
		
		## Other info
		$this->view->errors = $errors;
		$this->view->category_type = $type;
		$this->view->category_info = $info;
	}
	
	/*
		Function: addcategoryAction
	*/
	function addcategoryAction() {
		$request = new Cts_Request($this->getRequest());
		$Catalog = new CommerceMagentoCatalog();
		
		$args = array(
			'name'		=> $request->name,
			'is_active'	=> '1',
		);
		
		if( !Cts_ExtraResourceCheck::isAllowed("can_create_new_categories","commerce",$this->_identity->username) ){
			$this->session->errors = array('You do not have permission to create a new category.');
			$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/' );
		}
		
		if( !$request->has('season') ){
			$this->session->errors = array('No season selected when creating a new category. Please contact a developer.');
			$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/' );
		}
		
		if( !$request->has('activity') ){
			$this->session->errors = array('Please select an activity.');
			$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/' );
		} else {
			$season = $Catalog->getCategoryTree( $request->season );
			if( is_array($season) && count($season)>0 ){
				foreach( $season as $parentCat ){
					if( trim(strtolower($parentCat['name'])) == $request->activity ){
						$args['parentId'] = $parentCat['category_id'];
					}
				}
			}
		}
		
		if( !isset($args['parentId']) || empty($args['parentId']) ){
			$this->session->errors = array(ucwords($request->activity).' was not found in this season.');
			$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/' );
		}
		
		if( $request->has('name') && $request->has('type') && !empty($request->name) ){
			
			switch( $request->type ){
				case 'standard':
					$args['blackdiamond_swiftcollective_cat_is_hidden'] = '0';
					$args['blackdiamond_swiftcollective_cat_is_kit'] = '0';
					$args['blackdiamond_swiftcollective_cat_is_spareparts'] = '0';
					
					if( $request->has('comparisons') && $request->comparisons=='yes' ){
						$args['blackdiamond_swiftcollective_cat_allow_comparisons'] = '1';
					} else {
						$args['blackdiamond_swiftcollective_cat_allow_comparisons'] = '0';
					}
					break;
					
				case 'spare_parts':
					$args['blackdiamond_swiftcollective_cat_is_hidden'] = '0';
					$args['blackdiamond_swiftcollective_cat_is_kit'] = '0';
					$args['blackdiamond_swiftcollective_cat_is_spareparts'] = '1';
					$args['blackdiamond_swiftcollective_cat_allow_comparisons'] = '0';
					break;
					
				case 'kit':
					$args['blackdiamond_swiftcollective_cat_is_kit'] = '1';
					$args['blackdiamond_swiftcollective_cat_is_spareparts'] = '0';
					$args['blackdiamond_swiftcollective_cat_allow_comparisons'] = '0';
					
					if( $request->has('hidden') && $request->hidden=='yes' ){
						$args['blackdiamond_swiftcollective_cat_is_hidden'] = '1';
					} else {
						$args['blackdiamond_swiftcollective_cat_is_hidden'] = '0';
					}
					break;
			}
			
			$new_category = $Catalog->createCategory( $args['parentId'], $args );
			
			if(!$new_category){
				$this->session->errors = array('Category creation failed.');
				$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/' );
			} else {
				$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller."/edit/id/{$new_category}/");
			}
		} else {
			$this->session->errors = array('Please provide a Category name and activity.');
			$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/' );
		}
	}
	
	
	/*
		Function: addseasonAction
	*/
	function addseasonAction() {
		$request = new Cts_Request($this->getRequest());
		$Catalog = new CommerceMagentoCatalog();
		
		$activites = array(
			'Climb',
			'Ski',
			'Mountain',
		);
		
		$args = array(
			'name'													=> $request->name,
			'is_active'												=> '1',
			'blackdiamond_swiftcollective_cat_is_hidden'			=> '0',
			'blackdiamond_swiftcollective_cat_is_kit'				=> '0',
			'blackdiamond_swiftcollective_cat_is_spareparts'		=> '0',
			'blackdiamond_swiftcollective_cat_allow_comparisons'	=> '0',
		);
		
		if( !Cts_ExtraResourceCheck::isAllowed("can_create_new_seasons","commerce",$this->_identity->username) ){
			$this->session->errors = array('You must have global permissions to create a new season.');
			$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/' );
		}
		
		if( $request->has('name') && !empty($request->name) ){
			$new_season = $Catalog->createCategory( 1, $args );
			
			if( $new_season ){
				foreach( $activites as $activity ){
					$args['name'] = $activity;
					$args['is_active'] = '1';
					$args['url_key'] = strtolower($activity);
					
					$new_activity = $Catalog->createCategory( $new_season, $args );
				}
				
				$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/instance/global/season/'.$new_season.'/' );
			} else {
				$this->session->errors = array('Season creation failed.');
				$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/' );
			}
		} else {
			$this->session->errors = array('Please provide a name for the new season.');
			$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/' );
		}
	}
	
	
	/*
		Function: chooselocaleAction
	*/
	function chooselocaleAction() {
		$request = new Cts_Request($this->getRequest());
		
		$redirect = $request->locale.'/'.$request->module.'/'.$request->controller.'/';
		
		if( $request->has('redirect_to_action') ){
			$redirect .= str_replace('|','/',$request->redirect_to_action).'/';
		} else {
			$redirect .= "index/";
		}
		
		if( $request->has('id') ){
			$redirect .= "instance/{$request->id}/";
			$this->session->commerce_categoryadmin_selected_locale = $request->id;
		} else {
			$this->session->commerce_categoryadmin_selected_locale = NULL;
		}
		
		if( !empty($this->session->commerce_categoryadmin_selected_season) ){
			$redirect .= "season/{$this->session->commerce_categoryadmin_selected_season}/";
		}
		
		$this->_redirect( $redirect );
	}
	
	/*
		Function: chooseseasonAction
	*/
	function chooseseasonAction() {
		$request = new Cts_Request($this->getRequest());
		$redirect = $request->locale.'/'.$request->module.'/'.$request->controller.'/index/';
		
		if( !empty($this->session->commerce_categoryadmin_selected_locale) ){
			$redirect .= "instance/{$this->session->commerce_categoryadmin_selected_locale}/";
		}
		
		if( $request->has('id') ){
			$redirect .= "season/{$request->id}/";
			$this->session->commerce_categoryadmin_selected_season = (int)$request->id;
		} else {
			$this->session->commerce_categoryadmin_selected_season = NULL;
		}
		
		$this->_redirect( $redirect );
	}
	
	/*
		Function: changeseasonAction
	*/
	function changeseasonAction(){
		$request = new Cts_Request($this->getRequest());
		$Catalog = new CommerceMagentoCatalog();
		
		if( !$request->has('instance') || !$request->has('new_season') ){
			$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/' );
		} else {
			if( $request->instance==0 ){
				if( !Cts_ExtraResourceCheck::isAllowed("can_make_global_category_edits","commerce",$this->_identity->username) ){
					$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/' );
				} else {
					$stores = $Catalog->ddgetStores();
					
					foreach( $stores as $store=>$name ){
						$Catalog->setCurrentSeason( $store, $request->new_season );
					}
					
					$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/instance/global/season/'.$request->new_season );
				}
			} else {
				$Catalog->setCurrentSeason( $request->instance, $request->new_season );
				$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/index/instance/'.$request->instance.'/season/'.$request->new_season );
			}
		}
	}
	
	/*
		Function: do_associated_products
	*/
	function do_associated_products( $storeView, $request, $Catalog ){
		$associated_filters = array(
			'category_ids'	=> $request->id,
			'__no_children'	=> true,
			//'status'		=> array('like'=>'1'),
		);
		
		$associated_sort = array(
			'attribute'	=> 'name',
			'direction'	=> 'asc',
		);

		$associated_products = $Catalog->getProducts($associated_filters, $storeView, null, $associated_sort);
		
		if( $this->getRequest()->isPost() && $request->has('associated') && is_array($request->associated) ){
			$disassociate = array();
			foreach( $associated_products as $product ){
				if( !in_array($product['product_id'], $request->associated) ){
					$disassociate[] = $product['product_id'];
				} else {
					$key = array_search($product['product_id'],$request->associated);
					unset($request->associated[$key]);
				}
			}
			
			if( count($disassociate)>0 ){
				$Catalog->disassociateProducts( $request->id, $disassociate, 0 );	## Associate and disassociate globally
			}
			
			if( count($request->associated)>0 ){
				$Catalog->associateProducts( $request->id, $request->associated, 0 );	## Associate and disassociate globally
			}
			
			if( count($disassociate)>0 || count($request->associated)>0 ){
				## If any changes were made, get a new association list
				$associated_products = $Catalog->getProducts($associated_filters, $storeView, null, $associated_sort);
			}
			
		}
		
		return $associated_products;
	}
	
	
	/*
		Function: associateproductAction
	*/
	function associateproductAction(){
		$request = new Cts_Request($this->getRequest());
		$Catalog = new CommerceMagentoCatalog();
		
		$associate = $Catalog->associateProducts( $request->id, array($request->product), 0 );	## Associate and disassociate globally
		
		if( $associate ){
			die('associated');
		} else {
			die('error');
		}
	}
	
	/*
		Function: disassociateproductAction
	*/
	function disassociateproductAction(){
		$request = new Cts_Request($this->getRequest());
		$Catalog = new CommerceMagentoCatalog();
		
		$associate = $Catalog->disassociateProducts( $request->id, array($request->product), 0 );	## Associate and disassociate globally
		
		if( $associate ){
			die('disassociated');
		} else {
			die('error');
		}
	}
	
	/*
		Function: searchAction
	*/
	function searchAction() {
		$request = new Cts_Request($this->getRequest());
		$Catalog = new CommerceMagentoCatalog();
		
		$storeView = $Catalog->formatStoreId($this->use_locale);
		
		$filters = array();
		$filters['__no_children'] = true;
		
		if ( $request->has('name') ) {
			$filters['name'] = array( 'like' => "%{$request->name}%" );
		} elseif ( $request->has('sku') ) {
			$filters['sku'] = array( 'like' => "%{$request->name}%" );
		}
		
		$sort = array(
			'attribute'	=> 'name',
			'direction'	=> 'asc',
		);
		
		$products = $Catalog->getProducts($filters, $storeView, null, $sort);
		
		# Start XML return
		$dom = new DOMDocument();
		$dom->formatOutput = false;
		
		## Add printer information
		$root = $dom->createElement( 'results' );
		$dom->appendChild( $root );
		
		foreach ($products as $product) {
			$XMLProduct = $dom->createElement( 'product' );
			$XMLProduct->setAttribute( 'id', $product['product_id'] );
			$XMLProduct->setAttribute( 'name', $product['name'] );
			$XMLProduct->setAttribute( 'sku', $product['sku'] );

			if(isset($product['category_ids']) && is_array($product['category_ids']) && in_array($request->id, $product['category_ids'])){
				$XMLProduct->setAttribute('associated', 'yes');
			} else {
				$XMLProduct->setAttribute('associated', 'no');
				
			}

			$root->appendChild( $XMLProduct );
		}

		## Echo the XML
		header( "Content-type: text/xml" );
		echo $dom->saveXML();
		exit;
	}
	
	
	/*
		Function: povitemAction
	*/
	function povitemAction() {
		$request = new Cts_Request($this->getRequest());

		$this->view->active = '0';

		if ($request->has('title')) {
			$this->view->title = trim($request->title);
		}
		if ($request->has('subtitle')) {
			$this->view->subtitle = trim($request->subtitle);
		}
		if ($request->has('type')) {
			$this->view->type = trim($request->type);
		}
		if ($request->has('path')) {
			$this->view->path = trim($request->path);
		}
		if( $request->has('thumb') ){
			$this->view->thumb = trim($request->thumb);
		}
		if( $request->has('start') ){
			$this->view->start = date('Y-m-d H:i:s', strtotime($request->start));
			$this->view->start_formatted = date('m/d/Y', strtotime($request->start));
		} else {
			$this->view->start = date('Y-m-d H:i:s');
			$this->view->start_formatted = date('m/d/Y');
		}
		if( $request->has('end') && !empty($request->end) ){
			$this->view->end = date('Y-m-d H:i:s', strtotime($request->end));
			$this->view->end_formatted = date('m/d/Y', strtotime($request->end));
		} else {
			$this->view->end = '';
			$this->view->end_formatted = '(none)';
		}
	}
	
	
	/*
		Function: moveAction
	*/
	function moveAction() {
		$request = new Cts_Request($this->getRequest());
		$Catalog = new CommerceMagentoCatalog();

		if ($request->has('parent') && $request->has('categories')) {
			$categories = explode(',', $request->categories);
			for ($x = 0; is_array($categories), $x < count($categories); $x++) {
				$prev = (array_key_exists(($x-1), $categories)) ? $categories[($x-1)] : false;
				$move = $Catalog->moveCategory( $categories[$x], $request->parent, $prev );
				if(!$move) dd($move);
			}
		}

		echo 'It worked!';
	}
	
	
	/*
		Function: prepCategoryPage
		This function is mostly for handling global edit permissions, and fall through incase no locales are available
		though it does double as a method to provide locale data to the view.
	*/
	protected function prepCategoryPage( $request, $Catalog ){
		## Redirect to the full instance & season URL
		if( !$request->has('instance') || !$request->has('season') ){
			$redirect  = $request->locale.'/'.$request->module.'/'.$request->controller.'/'.$request->action.'/';
			
			if( $request->has('id') ){
				$redirect .= "id/$request->id/";
			}
			
			$redirect .= ($this->use_locale) ? "instance/$this->use_locale/" : 'instance/global/';
			$redirect .= "season/{$this->use_season}/";
			
			if( !$this->getRequest()->isPost() ){
				$this->_redirect( $redirect );
			} else {
				dd('This form should post to an address that includes the season and locale. Please contact a developer.');
			}
		}
		
		## Magento Store View Information
		$active_season_ids = array();
		$store_view_codes = $Catalog->getStores();
		foreach( $store_view_codes as $store_view_code=>$store_view_name ){
			$tmp_season_id = $Catalog->getCurrentSeasonId($store_view_code);
			$store_view_codes[$store_view_code] = array(
				'name' => $store_view_name,
				'current_season' => $tmp_season_id,
			);
			
			if( !in_array($tmp_season_id, $active_season_ids) ){
				$active_season_ids[] = $tmp_season_id;
			}
		}
		
		$available_locales = array();
		$locales_table = new Locales();
		$locale_codes = $locales_table->getLocaleCodesArray(false);
		
		if( Cts_Registry::get('force_global_category_edits') == '0' ){
			$allowed_locales = explode(',', Cts_Registry::get('allowed_locales'));	
		} else {
			$allowed_locales = false;
		}
		
		if( is_array($allowed_locales) && array_filter($allowed_locales) ){
			## If the user is trying to access global edits but doesn't have permission, pick another locale to edit.
			if( !$this->use_locale && !Cts_ExtraResourceCheck::isAllowed("can_make_global_category_edits","commerce",$this->_identity->username) ){
				$this->session->commerce_categoryadmin_selected_locale = $Catalog->formatStoreId($this->locale_code);
				$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller.'/' );
			}
			foreach( $locale_codes as $locale_code => $locale ){
				if( in_array($locale_code, $allowed_locales) ){
					$locale_code = $Catalog->formatStoreId($locale_code);
					if( array_key_exists($locale_code, $store_view_codes) ){
						$available_locales[$locale_code] = $locale;
					}
				}
			}
		} elseif( $this->use_locale ){
			$this->session->commerce_categoryadmin_selected_locale == 'global';
			$this->_redirect( $request->locale.'/'.$request->module.'/'.$request->controller."/index/instance/global/season/{$this->use_season}/" );
		} elseif( !Cts_ExtraResourceCheck::isAllowed("can_make_global_category_edits","commerce",$this->_identity->username) ){
			$this->view->errors = array('You do not have permission to edit categories globally, and no other locales are available.');
			$this->view->all_stop = true;
			return;
		}
		
		if( Cts_ExtraResourceCheck::isAllowed("can_make_global_category_edits","commerce",$this->_identity->username) ){
			$this->view->global_edits = 'yes';
		} else {
			$this->view->global_edits = 'no';
		}
		
		$this->view->available_locales = $available_locales;
		$this->view->editing_store = $Catalog->formatStoreId($this->use_locale);
		
		## Setup Seasons
		$all_seasons = array();
		$active_seasons = array();
		$inactive_seasons = array();
		$seasons = Commerce_Common::getSeasons( $this->use_locale );
		foreach( $seasons as $season ){
			$all_seasons[ $season['category_id'] ] = $season;
			if( in_array($season['category_id'], $active_season_ids) ){
				$active_seasons[ $season['category_id'] ] = $season;
			} else {
				$inactive_seasons[ $season['category_id'] ] = $season;
			}
		}
		
		if( $this->use_season ){
			$this->view->selected_season = $all_seasons[ $this->use_season ];
		} else {
			$this->view->selected_season = $active_seasons[0];
		}
	
		$this->view->all_seasons = $all_seasons;
		$this->view->active_seasons = $active_seasons;
		$this->view->inactive_seasons = $inactive_seasons;
		
		## Category Tree
		$this->view->magento_root_catalog_level = Cts_Registry::get('magento_root_catalog_level');
		$this->view->magento_root_category_level = Cts_Registry::get('magento_root_category_level');
		$this->view->magento_subcategory_level = Cts_Registry::get('magento_subcategory_level');
		$this->view->category_tree = Commerce_Common::categoryTree( false, $this->use_locale, $this->use_season );
		
		## Permissions
		$this->view->can_make_global_category_edits = Cts_ExtraResourceCheck::isAllowed("can_make_global_category_edits","commerce",$this->_identity->username);
		$this->view->can_create_new_seasons = Cts_ExtraResourceCheck::isAllowed("can_create_new_seasons","commerce",$this->_identity->username);
		$this->view->can_change_seasons = Cts_ExtraResourceCheck::isAllowed("can_change_seasons","commerce",$this->_identity->username);
		$this->view->can_create_new_categories = Cts_ExtraResourceCheck::isAllowed("can_create_new_categories","commerce",$this->_identity->username);
	}
	
	function simplifyAttributeNames( $info ){
		foreach( $info as $key=>$value ){
			if( strstr($key, 'blackdiamond_swiftcollective_') !== false ){
				$new_key = str_replace('blackdiamond_swiftcollective_', 'bdsc_', $key);
				$info[$new_key] = $value;
				unset($info[$key]);
			}
		}
		return $info;
	}
	
	function restoreAttributeNames( $info ){
		foreach( $info as $key=>$value ){
			if( strstr($key, 'bdsc_') !== false ){
				$new_key = str_replace('bdsc_', 'blackdiamond_swiftcollective_', $key);
				$info[$new_key] = $value;
				unset($info[$key]);
			}
		}
		return $info;
	}
}
